from google.appengine.ext import webapp
from google.appengine.ext import db
from lib import datastore

def create_tag(tagName, imageKey):
    
    tag = datastore.Tag()
    tag.name = tagName
    tag.imageKey = imageKey
    tagKey = tag.put()
    return tagKey

def remove_tag(tagName, imageKey):
    
    results = db.GqlQuery("SELECT * FROM Tag WHERE name = :1 and imageKey = :2", tagName, imageKey)
    if results.count():
        tag = results[0]
        tag.delete()

class TagHandler(webapp.RequestHandler):
    '''This handler modifies tags in images'''
     
    def post(self, key):
        
        photo = datastore.get_photo(self, key)
        tags = photo.tags.split()
        tagName = self.request.get("remove")
        if tagName:
            #remove tag from database
            remove_tag(tagName, key)
            
            #remove tag from list
            if tagName in tags:
                tags.remove(tagName.lower())
        else:                        
            #create and update tags
            newTags = self.request.get('tags').split()
            for tag in newTags:
                tag = tag.lower() #normalize it to lower-case
                if not tag in tags:
                    tags.append(tag)
                    tagKey = create_tag(tag, key)
            tags.sort()
        
        photo.tags = ' '.join(tags)
        photo.put()
        self.redirect('/view/%s' %key)